package com.ibiz.znjd.znjd;

import android.os.Handler;

import com.getcapacitor.JSObject;
import com.ibiz.znjd.MainApplication;

import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 活动轨迹管理类
 */
public class GjInternal {
    /**
     * 请求接口（测试保活）
     * @param type
     */
    public static void testAlive(String type) {
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder().url("http://172.16.103.13:3000/record?type="+type).build();
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                if(response.isSuccessful()){
//                    String result = response.body().string();
//                    //处理UI需要切换到UI线程处理
//                }
//            }
//        });
        System.out.println("日志："+type);
    }

    /**
     * 发送定位轨迹
     * @param app
     */
    public static void send(MainApplication app){
        // 监管方式不为20时,关闭手机的轨迹功能
        String jgfs = app.envMap.get("jgfs");
        if(!"20".equals(jgfs)){
            System.out.println("监管方式为"+jgfs+",不上传轨迹");
            return;
        }

        System.out.println("开始上传轨迹");
        JSObject location = app.getLocationService().locationObj;
        String locusUrl = app.envMap.get("locusUrl");
        String token = app.envMap.get("token");
        String personid = app.envMap.get("personid");
        if(location == null || locusUrl == null || token == null || personid == null){
            return;
        }

        // 当前时间
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String time = sdf.format(date);

        // 发起请求
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        JSONObject json = new JSONObject();
        try {
            json.put("personid", personid);
            json.put("jgbdsj", time);
            json.put("lng", location.getDouble("longitude"));
            json.put("lat", location.getDouble("latitude"));
            json.put("jgbddd", location.getString("addr"));
        }catch (Exception e){
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON,json.toString());
        Request request = new Request.Builder()
                .header("Authorization", "Bearer " + token)
                .header("deviceType", "app")
                .url(locusUrl)
                .post(body)
                .build();
        Call call = client.newCall(request);

        System.out.println("轨迹请求参数："+json.toString());
        System.out.println("轨迹请求url："+locusUrl);
        System.out.println("轨迹请求token："+token);

        // 请求回调
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("上传轨迹失败！");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if(response.isSuccessful()){
                    //处理UI需要切换到UI线程处理
                    System.out.println("上传轨迹成功："+result);
                }else{
                    System.out.println("上传轨迹失败："+result);
                }
                System.out.println(result);
            }
        });
    }

    /**
     * 开启定时器
     * @param app 应用对象
     */
    public static Handler startInternal(MainApplication app){
        // 设置定时器
        Handler mHandler = new Handler();
        Runnable r = new Runnable() {

            @Override
            public void run() {
                GjInternal.send(app);
                //每隔1s循环执行run方法
                mHandler.postDelayed(this, 1000*60*10);
            }
        };
        mHandler.postDelayed(r, 100);//延时100毫秒
        return mHandler;
    }

}
